package com.dhecp.project.system.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.layui.TreeDataModel;
import com.dhecp.core.layui.TreeSelectDataModel;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.OrgSimple;
import com.dhecp.project.system.domain.SysDataFolder;
import com.dhecp.project.system.mapper.SysDataFolderMapper;
import com.dhecp.project.system.service.SysDataFolderService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 资料文件夹
 * @author DH-Xxj
 * @version 2019年9月19日
 */

@Service
public class SysDataFolderServiceImpl implements SysDataFolderService {
    
	@Autowired
	private SysDataFolderMapper dataFolderMapper;
	
	@Autowired
	private SysDictionaryForFieldService dictionaryForFieldService;


	/**
	 * 通过guid查询单条记录
	 * @param guid
	 * @return DataFolder
	 * @author DH-Xxj
	 */
	@Override
	public SysDataFolder queryDataFolderByGuid(String guid){
		return dataFolderMapper.findDataFolderByGuid(guid);
	}

	/**
	 * 直接查询资料文件夹表的数据
	 * @param params
	 * @return List-DataFolder
	 * @author DH-Xxj
	 * @throws Exception 
	 */
	@Override
	public List<SysDataFolder> queryDataFolder(Map<String, Object> params) throws Exception{
//        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
//		PageUtils.startPage();
		return dataFolderMapper.findDataFolder(params);
	}
	
	/**
	 * 查询调入资料文件夹对象
	 * @param params
	 * @return List - DataFolder
	 * @author DH-Xxj
	 * @throws Exception 
	 */
	@Override
	public List<SysDataFolder> queryDataFolderObject(Map<String, Object> params) throws Exception{
		params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
		params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
		PageUtils.startPage();
		return dataFolderMapper.findDataFolderObject(params);
	}
	
	/**
	 * 部门列表
	 * @param params
	 * @return List-DataFolder
	 * @author kimiloo
	 * @throws Exception 
	 */
	@Override
	public List<SysDataFolder> queryDeptInfo(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
		PageUtils.startPage();
		return dataFolderMapper.findDeptInfo(params);
	}

	/**
	 * 获取资料文件夹树
	 * @param params
	 * @return List-TreeDataModel
	 * @author DH-Xxj
	 */
	@Override
	public List<TreeDataModel> queryDataFolderTree(Map<String, Object> params){
		return dataFolderMapper.findDataFolderTree(params);
	}

	/**
	 * 获取资料文件夹树（含复选框）
	 * @param params
	 * @return List-TreeSelectDataModel
	 * @author DH-Xxj
	 */
	@Override
	public List<TreeSelectDataModel> queryDataFolderTreeSelect(Map<String, Object> params){
		return dataFolderMapper.findDataFolderTreeSelect(params);
	}
	
	/**
	 * 获取排除用户的资料文件夹树（含复选框）
	 * @param params
	 * @return List-TreeSelectDataModel
	 * @author DH-Xxj
	 */
	@Override
	public List<TreeSelectDataModel> queryDataFolderTreeSelectNoUser(Map<String, Object> params){
		return dataFolderMapper.findDataFolderTreeSelectNoUser(params);
	}
	
	/**
	 * 新增文件夹节点（公司、部门）
	 * @param params
	 * 		必要参数：pguid（上级文件夹唯一值guid，顶级默认值（'root'））
	 * 		必要参数：folderName（新增文件夹名称）
	 * @return MessageModel
	 * @author DH-Xxj
	 * @throws Exception 
	 */
	@Override
	public AjaxResult insertDataFolder(Map<String, Object> params) throws Exception{
    	if (params.get("pguid") == null || params.get("pguid") == ""){
			return AjaxResult.error("请提供必要的参数[上级文件夹唯一值]：pguid");
    	}else if (params.get("folderName") == null || params.get("folderName") == ""){
			return AjaxResult.error("请提供必要的参数[文件夹名称]：folderName");
        }else{
        	params.put("createTime", new Date());
        	params.put("updateTime", new Date());
			dataFolderMapper.insertDataFolder(params);
			return AjaxResult.success("操作成功");
        }
	}

	
	/**
	 * 分配管理者
     * @param guid 必要参数： 要分配管理者的文件夹唯一值
     * @param userList 必要参数：对应实体类的json格式字符串(orgid:用户编号)
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult insertOrgManagersByGuid(Map<String, Object> params) throws Exception{
		if (params.get("guid") == null || params.get("guid") == ""){
			return AjaxResult.error("请提供必要的参数[要分配管理者的文件夹唯一值]：guid");
		}else if (params.get("userList") == null || params.get("userList") == ""){
			return AjaxResult.error("缺少参数userList【对应实体类的json格式字符串】。");
		}else{
			List<OrgSimple> userList = JSON.parseArray(params.get("userList").toString(), OrgSimple.class);
			if (userList == null || userList.size() == 0) {
				return AjaxResult.error("数据包格式有误，请检查！");
			}
			String orgids = "";
			for (OrgSimple userInfo : userList){
				String orgid = "[" + userInfo.getOrgid() + "]";
				if ("".equals(orgids)){
					orgids = orgid;
				}else if (orgids.indexOf(orgid) == -1){
					orgids = orgids + "," + orgid;
				}
			}
			String folderManagers = "";
			SysDataFolder dataFolder = dataFolderMapper.findDataFolderByGuid(params.get("guid").toString());
			if (dataFolder == null){
				return AjaxResult.error("系统未检测到您选择的文件夹，可能已被其他用户删除，请刷新页面后重试。");
			}else{
				folderManagers = dataFolder.getFolderManagers();
				if ("".equals(folderManagers)){
					folderManagers = orgids;
				}else if (folderManagers.indexOf(orgids) == -1){
					folderManagers = folderManagers + "," + orgids;
				}
			}
			params.put("folderManagers", folderManagers);
			params.put("updateTime", new Date());
			dataFolderMapper.updateOrgManagersByGuid(params);
			return AjaxResult.success("操作成功");
    	}		
	}	
	
	/**
	 * 通过orgPathAll删除文件夹及其子树
	 * @param params
	 * 		必要参数：orgPathAll（要删除的文件夹全路径）
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult deleteSubtreeByOrgPathAll(Map<String, Object> params) throws Exception{
    	if (params.get("orgPathAll") == null || params.get("orgPathAll") == ""){
			return AjaxResult.error("请提供必要的参数[文件夹全路径]：orgPathAll");
    	}else{
    		dataFolderMapper.deleteSubtreeByOrgPathAll(params);
			return AjaxResult.success("操作成功");
    	}		
	}

	/**
	 * 删除管理者
	 * @param params
	 * 		必要参数：guid（要删除管理者的文件夹唯一值） 
	 * 		必要参数：orgid（要删除的管理者用户编号）
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult deleteOrgManagersByGuid(Map<String, Object> params) throws Exception{
    	if (params.get("guid") == null || params.get("guid") == ""){
			return AjaxResult.error("请提供必要的参数[要删除管理者的文件夹唯一值]：guid");
    	}else if (params.get("orgid") == null || params.get("orgid") == ""){
			return AjaxResult.error("请提供必要的参数[要删除的管理者用户编号]：orgid");
    	}else{  
        	String folderManagers = "";
        	String orgid = "[" + params.get("orgid").toString() + "]";
			SysDataFolder dataFolder = dataFolderMapper.findDataFolderByGuid(params.get("guid").toString());
    		if (dataFolder == null){
				return AjaxResult.error("系统未检测到您选择的文件夹，可能已被其他用户删除，请刷新页面后重试。");
    		}else{
    			folderManagers = dataFolder.getFolderManagers();
    			if (folderManagers.indexOf("," + orgid) != -1){
    				folderManagers = folderManagers.replace("," + orgid, "");
    			}
    			if (folderManagers.indexOf(orgid + ",") != -1){
    				folderManagers = folderManagers.replace(orgid + ",", "");
    			}
    			if (folderManagers.indexOf(orgid) != -1){
    				folderManagers = folderManagers.replace(orgid, "");
    			}
    		}
    		params.put("folderManagers", folderManagers);
    		params.put("updateUser", ShiroUtils.getUserId());
    		params.put("updateTime", new Date());
			dataFolderMapper.updateOrgManagersByGuid(params);
			return AjaxResult.success("操作成功");
    	}		
	}	
	
	/**
	 * 通过guid修改文件夹名称
	 * @param params
	 * 		必要参数：guid（要修改的文件夹唯一值） 
	 * 		必要参数：folderName（修改后的文件夹名称）
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult updateFolderNameByGuid(Map<String, Object> params) throws Exception{
    	if (params.get("guid") == null || params.get("guid") == ""){
			return AjaxResult.error("请提供必要的参数[要修改的文件夹唯一值]：guid");
    	}else if (params.get("folderName") == null || params.get("folderName") == ""){
			return AjaxResult.error("请提供必要的参数[修改后的文件夹名称]：folderName");
    	}else{
    		params.put("updateUser", ShiroUtils.getUserId());
    		params.put("updateTime", new Date());
			dataFolderMapper.updateFolderNameByGuid(params);
			
			return AjaxResult.success("操作成功");
    	}		
	}
	
	/**
	 * 通过guid修改文件夹行号
	 * @param params
	 * 		必要参数：guid（要修改的文件夹唯一值） 
	 * 		必要参数：iid（修改后的行号）
	 * @return MessageModel
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult updateIidByGuid(Map<String, Object> params) throws Exception{
		List<SysDataFolder> dataFolderList = JSON.parseArray(params.get("infoItems").toString(), SysDataFolder.class);
		if (dataFolderList == null || dataFolderList.size() == 0) {
			return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
		}
		for (SysDataFolder dataFolderInfo : dataFolderList) {
			dataFolderMapper.updateIidByGuid(dataFolderInfo);
		}
		return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
	}

}
